<?php
/**
 * 产品管理
 * @author cjli
 *
 */
class ProductAction extends AdminAction
{
	public function _initialize()
	{
		parent::_initialize();
	}
	
	public function index()
	{

		$post = $_REQUEST;
		
		//$language_id = C('language_id') ? C('language_id') : 1;
		$language_id = 6;
		$where = array(
				'product.is_delete' => 0,
		);
        
        $is_accessories = false;
		//搜索分类
		if(isset($post['catid']) && $post['catid']){
			$cat_ids = CategoryModel::getCategoryChildIds($post['catid']);
			$where['product.catid'] =  array('in', $cat_ids);
			$catid = $post['catid'];
			$this->assign('catid', $post['catid']);
			if($post['catid'] == 2067){
                $is_accessories = true;
			}else{
				$parentid = D('category')->where(array('id'=>$post['catid']))->getField('parentid');
				if($parentid == 2067) $is_accessories = true;
			}
		}
		
		
		//搜索产品类型
		if(isset($post['modelid']) && $post['modelid']){
			$where['product.model_id'] = $post['modelid'];
			$this->assign('modelid', $post['modelid']);
		}
		//搜索设计师
		if(isset($post['designer_id'])){
			if($post['designer_id'] != -1) $where['product.designer_id'] = $post['designer_id'];
			$this->assign('designer_id', $post['designer_id']);
		}
		//搜索是否预售
		if($post['product_type'] != ''){
			$where['product.product_type'] = $post['product_type'];
			$this->assign('product_type', $post['product_type']);
		}

		//搜索是否上下架
		if($post['display'] != ''){
			$where['product.display'] = $post['display'];
			$this->assign('display', $post['display']);
		}

		//搜索推荐
		if(isset($post['recommendid']) && $post['recommendid']){
			$where['cp.catid'] = $post['recommendid'];
			$this->assign('recommendid', $post['recommendid']);
		}

		//搜索关键词
		if(isset($post['keyword']) && $post['keyword']){
			if($post['searchtype'] == 2)
			{
				$where['product.id'] = $post['keyword'];
            	$catid = D('product')->where(array('id'=>$post['keyword']))->getField('catid');
            	$parentid = D('category')->where(array('id'=>$catid))->getField('parentid');
            	if($catid == 2067 || $parentid ==2067 ){
            		$is_accessories = true;
            	}				
			}elseif($post['searchtype'] == 1)
			{
				$where['product.sn'] = $post['keyword'];
			}elseif($post['searchtype'] == 3)
            {
                $where['product.eng_id'] = $post['keyword'];
            }elseif($post['searchtype']==4){
				$condition['suppliers_name'] = array('like', '%'.$post['keyword'].'%');
				$suppliers_res=D("suppliers")->where($condition)->select();
				if(!empty($suppliers_res)){
					$suppliers_id_arr = array();
					foreach($suppliers_res as $val_suppliers){
						array_push($suppliers_id_arr,$val_suppliers['suppliers_id']);
					}
					$where1['product.suppliers_id'] = array("in",$suppliers_id_arr);
				}
				if(isset($where1)){
					$where2['pri.name'] = array('like', '%'.$post['keyword'].'%');
					$where=array($where1,$where2,'_logic'=>'or');
				}else{
					$where['pri.name'] = array('like', '%'.$post['keyword'].'%');
				}
			}
			$this->assign('keyword', $post['keyword']);
		}
		$this->assign('searchtype', $post['searchtype']);

		//搜索是否预售
		if($post['product_type'] != ''){
			$where['product.product_type'] = $post['product_type'];
		}
		
		//order by
		if(isset($_REQUEST['sort_by']) && $_REQUEST['sort_by']){
			$sort_by = $_REQUEST['sort_by'];
		}else{
			$sort_by = 'DESC';
		}
		
		if(isset($_REQUEST['order_by']) && $_REQUEST['order_by']){
			$order_by = $_REQUEST['order_by'];
		}else{
			$order_by = 'id';
		}
		
//		dump($where);exit;
        //到出产品数据
        if( intval($_REQUEST['doexcel']) ==1 ){
            $this->list_doexcel($where, $order_by, $sort_by);exit;
        }

		$product_db = M('product');

		//分页
		if(isset($_SESSION['search']['recommendid'])){
			$product_db->join('category_product as cp on cp.pid=product.id');
		}
		
		
		$pageRows = isset($_SESSION['product_pageRows']) ? $_SESSION['product_pageRows'] : 20;
		if(isset($_REQUEST['pageRows']) && intval($_REQUEST['pageRows'])){
			$pageRows = intval($_REQUEST['pageRows']);
			$_SESSION['product_pageRows'] = $pageRows;
		}
		
		$product_db->where($where);
		$count = $product_db->count();//总记录数
//		echo $product_db->getLastSql();exit;
		import("ORG.Util.Page");// 导入分页类
		$Page = new Page($count, $pageRows);// 实例化分页类 传入总记录数和每页显示的记录数
		$pageShow = $Page->show();// 分页显示输出
		$this->assign('pageShow', $pageShow);
		$nowPage = $Page->getNowPageUrl();//当前页url
		//如果是post过来的则跳转到带参数的url
		if($_POST){
			if($nowPage){
		    	redirect($nowPage);exit;
			}
		}
		//保存当前url
		cookie('product_list_nowPage',$nowPage);			
		//$where['pri.language_id']= $language_id;
		
		//产品列表
//		$product_db->field('product.id');
		$product_db->field('product.eng_id,product.id,product.catid,product.brand_id,product.sn,pri.name,product.sell_price,product.market_price,product.visit,product.stock,product.listorder,product.display,product.custom_price,product.advanced_price,product.is_sell,product.product_type,product.sorts,product.small_img,product.suppliers_id');
		$product_db->join('product_items AS pri ON product.id=pri.product_id and pri.language_id='.$language_id);
		$product_db->order('product.listorder DESC, product.id DESC');
		$product_db->limit($Page->firstRow.','.$Page->listRows);
		$product_db->group('product.id');
		$product_db->where($where);
		$product_db->order( $order_by.' '. $sort_by);
		
		if(isset($_SESSION['search']['recommendid'])){
			$product_db->join('category_product as cp on cp.pid=product.id');
		}
		$productList = $product_db->select();
		//echo M()->getLastSql();


		if($productList){
			$categoryList = CategoryModel::getCategoryListBase();
//			$brandList = CategoryModel::getCategoryListBase(CategoryModel::TYPE_BRAND);
			foreach ($productList as &$product){
				$product['catname'] = '';
//				$product['brand_name'] = '';
				if($product['catid']){
					foreach ($categoryList as $cat){
						if($product['catid'] == $cat['id']){
							$product['catname'] = $cat['name'];
							break;
						}
					}
				}
//				if($product['brand_id']){
//					foreach ($brandList as $brand){
//						if($product['brand_id'] == $brand['id']){
//							$product['brand_name'] = $brand['name'];
//							break;
//						}
//					}
//				}
				if($is_accessories){
					$product['surplus'] = SuppliersModel::inventorySurplus(2,$product['id']);
				}
			}
			unset($product);
		}

//dump($productList);exit;
		$this->assign('productList', $productList);
		//下拉分类
		$catid = isset($catid) ? $catid : 0;
		$select_categorys = CategoryModel::categorySelectList($catid); 
		$this->assign('select_categorys', $select_categorys);
		//属性类型列表
		$modelList = AttributeModel::getModelList(); 
		$this->assign('modelList', $modelList);
		//推荐数组
		$recommendArray = array();
		$recommends = CategoryModel::getCategoryListBase(CategoryModel::TYPE_RECOMMEND);
		foreach ($recommends as $cat){
			$recommendArray[$cat['id']] = $cat['name'];
		}
		$this->assign('recommendArray', $recommendArray);

		//设计师列表
		$designerList = UserModel::getUserDesignerList();
		$this->assign('designerList', $designerList);
        
        $this->assign('is_accessories', $is_accessories);
		$this->assign('search', isset($_SESSION['search']) ? $_SESSION['search'] : null);
		$this->assign('pageRows', $pageRows);
		$this->assign('sort_by', $sort_by);
		$this->assign('order_by', $order_by);
		$this->display('product_list');
	}

	public function list_doexcel($where, $order_by, $sort_by){
        //excel daochu
            $language_id = 1;
            $where['pri.language_id'] = C("language_id");
            $product_db = M('product');
			$product_db->field('sup.suppliers_name,product.id,product.catid,product.brand_id,product.sn,pri.name,product.eng_id,
				product.sell_price,product.market_price,product.visit,product.stock,product.listorder,
				product.display,product.custom_price,product.advanced_price,product.is_sell,product.product_type,
				product.sorts,pri.summary,product.attribute_type,pri.content,product.colour_id,product.product_colour_id');
			$product_db->join('product_items AS pri ON product.id=pri.product_id');
			$product_db->join('suppliers AS sup ON product.suppliers_id=sup.suppliers_id');
			$product_db->order('product.listorder DESC, product.id DESC');
			//$product_db->limit($Page->firstRow.','.$Page->listRows);
			$product_db->group('product.id');
			$product_db->where($where);
			$product_db->order( $order_by.' '. $sort_by);
			$productList = $product_db->select();

			import('COM.XmlExcel');
			$excel=new XmlExcel;
			$excel_title= array('id','标题','货号','description','google product category',
				'product type','link','image link','additional image link','condition',
				'availability','price','brand','color','material','pattern','tax','suppliers_name');

			$excel->addHead($excel_title); //设置CSV文件标题

			$categoryList = array();
			//产品颜色数据
	        $categoryListRes = CategoryModel::getCategoryList(11);
	        foreach ($categoryListRes as $category) {
	            $categoryList[$category['id']] = $category;
	        }    
		    foreach ($productList as $key => $val) {
                //颜色
                $product_colour_id = explode(",",$val['product_colour_id']); 
                $product_colour = "";
                foreach ($product_colour_id as $id) {
                    if($product_colour) $product_colour .= ',';
                    $product_colour .= $categoryList[$id]['name'];  
                }   	
		    	$addRowData = array();
                $addRowData[] = $val['id'];
                $addRowData[] = $val['name'];
                $addRowData[] = $val['eng_id'];
                $addRowData[] = $val['summary'];
                $addRowData[] = '';

                $catifno = CategoryModel::getCategoryInfo($val['catid'], $language_id);
                if($catifno['parentid']>0) $catifno = CategoryModel::getCategoryInfo($catifno['parentid'], $language_id);
                $addRowData[] = $catifno['name'];

                $addRowData[] = 'http://www.ownonly.com'.'/product/'.$val['id'].'-'.generateUrl_un($val['name']);
                $photoList = ProductModel::getProductPhotoList($val['id'], 0);
                $addRowData[] = 'http://www.ownonly.com'.$photoList[0]['img'];
                $addRowData[] = 'http://www.ownonly.com'.$photoList[1]['img'];
                $addRowData[] = 'new';
                $addRowData[] = 'in stock';
                if($val['attribute_type'] == 1){
                    $addRowData[] = $val['custom_price']; 
                }else{
                	$addRowData[] = $val['advanced_price']; 
                }
                $addRowData[] = 'OWNONLY';           
                $addRowData[] = $product_colour;   
                $addRowData[] = strip_tags($val['content']); 

                $pattern = '';
                if($val['colour_id']){
                    $colour_ids= explode(',', $val['colour_id']);
                    foreach($colour_ids as $cids_v){
                        if(intval($cids_v) > 0){
                        	$catifno = CategoryModel::getCategoryInfo($cids_v, $language_id);
                        	if($catifno) $pattern .= $catifno['name'].',';
                        } 
                    }
                    if(!empty($pattern)) $pattern = trim($pattern, ',');
                }
                $addRowData[] = $pattern;
                $addRowData[] = 'US::0:';
                $addRowData[] = $val['suppliers_name'];

			    $excel->addRow($addRowData);
		    }
    
		    $excel_name = '产品数据'.'-'.date('Y-m-d H:i');
		    $excel->export($excel_name);
			exit;

	}
	
	//下拉批量修改
	public function beach_select_edit()
	{
		if($_POST['dosubmit']){
			$pids = $_POST['pids'];
			$type = trim($_POST['type']);
			$product_db = D('product');
			$pids = array_filter($pids);
			if($pids && $type)
			{
				$where['id'] = array('in', $pids);
				//设置推荐
				if(is_numeric($type))
				{
					$category_product_db = D('category_product');
					$where = array(
						'catid' => $type,
						'pid' => array('in', $pids),
					);
					$category_product_db->where($where)->delete();
					foreach ($pids as $pid){
						$data = array(
							'catid' => $type,
							'pid' => $pid,
						);
						$category_product_db->add($data);
					}
				}
				//取消推荐
				elseif(substr($type,-3) == '_no')
				{
					$types = explode('_', $type);
					$category_product_db = D('category_product');
					$where = array(
						'catid' => intval($types[0]),
						'pid' => array('in', $pids),
					);
					$category_product_db->where($where)->delete();
				}
				//回收站
				elseif($type == 'trash')
				{
					foreach ($pids as $pid){
						$product_db->where('id='.$pid)->save(array('is_delete' => 1));
						ProductModel::deleteProductCache($pid);
						
						//删除购物车的产品
						$where = array(
							'pid' => is_array($pid) ? array('IN', join(',', $pid)) : $pid,
						);
						$cart_db = D('cart_products');
						$cart_db->where($where)->delete();
					}
				}
				//上架
				elseif($type=="on_sale")
				{
					$product_db->where($where)->save(array('display' => 1));
					foreach ($pids as $pid)
						ProductModel::deleteProductCache($pid);
				}
				//下架
				elseif ($type=="not_on_sale")
				{
					$product_db->where($where)->save(array('display' => 0));
					foreach ($pids as $pid)
						ProductModel::deleteProductCache($pid);
				}
				//转移分类
				elseif($type=="move_to")
				{
					if(intval($_POST['catid'])){
						$product_db->where($where)->save(array('catid' => intval($_POST['catid'])));
					}
				}elseif($type=='suppliers_move_to'){
					if(intval($_POST['suppliers_id'])){
						$product_db->where($where)->save(array('suppliers_id' => intval($_POST['suppliers_id'])));
					}
				}
			}
		}
		$this->success('操作成功！',U('product/index'));
	}
	
	//批量修改
	public function beach_edit()
	{
		if(isset($_POST['dosubmit']))
		{
			if($_POST['select_method'] == 'cat'){
				$productIds = trim($_POST['goods_ids']);
				$where['product.id'] = array('IN', $productIds);
			}else{
				$snList = trim($_POST['sn_list']);
				$where['product.sn'] = array('IN', explode("\n", str_replace("\r", '', $snList)));
			}
			//$where['product.display'] = 1;
			$where['product_items.language_id'] = C('language_id');
		
			$product_db = D('product');
			$product_db->field('id,name,sn,brand_id,sell_price,market_price,cost_price,stock,rank_integral,integral,small_img,suppliers_id');
			$product_db->join('product_items ON product_items.product_id = product.id');
			$productList = $product_db->where($where)->select();
			
			if(!$productList)
				$this->error('请选择产品', U('product/beach_edit'));
				
			$this->assign('productList', $productList);
			
			//供货商
			$suppliersList = SuppliersModel::getSuppliersList();
			$this->assign('suppliersList', $suppliersList);
			
			$brandList = CategoryModel::getCategoryListBase(CategoryModel::TYPE_BRAND);
			$this->assign('brandList', $brandList);
			$this->assign('edit_method', $_POST['edit_method']);
			$this->display('beach_edit_update');
		}else{
			$categorySelectList = CategoryModel::categorySelectList();
			$brandList = CategoryModel::getCategoryListBase(CategoryModel::TYPE_BRAND);
			$this->assign('categorySelectList', $categorySelectList);
			$this->assign('brandList', $brandList);
			$this->display('beach_edit');
		}
	}
	
	//批量修改更新
	public function beach_edit_update()
	{
			if($_POST['dosubmit']){
				$product_db = D('product');
				
				$edit_method = $_POST['edit_method'];
				if($edit_method == 'each')
				{
					$productList = $_POST['product'];
					if($productList){
						foreach ($productList as $pid => $pro){
							$data = array(
								'brand_id' => intval($pro['brand_id']),
								'suppliers_id' => intval($pro['suppliers_id']),
								'sell_price' => floatval($pro['sell_price']),
								'market_price' => floatval($pro['market_price']),
								'cost_price' => floatval($pro['cost_price']),
								'custom_price' => floatval($pro['custom_price']),
								'advanced_price' => floatval($pro['advanced_price']),
//								'product_type' => intval($pro['product_type']),
								'end_time' => time(),
								'rank_integral' => (isset($pro['rank_integral']) && $pro['rank_integral']!=-1) ? intval($pro['rank_integral']) : -1,
								'integral' => (isset($pro['integral']) && $pro['integral']!=-1) ? intval($pro['integral']) : -1,
							);
							$product_db->where('id='.$pid)->save($data);
							ProductModel::deleteProductCache($pid);
						}
					}
				}else{
					$pro = $_POST;
					$productIds = explode(',', $_POST['product_ids']);
					foreach ($productIds as $pid){
						if(!is_numeric($pid))continue;
						$data = array(
								'brand_id' => intval($pro['brand_id']),
								'suppliers_id' => intval($pro['suppliers_id']),
								'sell_price' => floatval($pro['sell_price']),
								'market_price' => floatval($pro['market_price']),
								'cost_price' => floatval($pro['cost_price']),
								'custom_price' => floatval($pro['custom_price']),
								'advanced_price' => floatval($pro['advanced_price']),
//								'product_type' => intval($pro['product_type']),
								'stock' => intval($pro['stock']),
								'end_time' => time(),
								'rank_integral' => (isset($pro['rank_integral']) && $pro['rank_integral']!=-1) ? intval($pro['rank_integral']) : -1,
								'integral' => (isset($pro['integral']) && $pro['integral']!=-1) ? intval($pro['integral']) : -1,
							);
						$product_db->where('id='.$pid)->save($data);
						ProductModel::deleteProductCache($pid);
					}
				}
			}
			$this->success('批量编辑完成', U('product/beach_edit'));
	}
	
	//ajax下拉获取产品列表
	public function goods_batch_ajax()
	{
		$cat_id = intval($_GET['cat_id']);
		$brand_id = intval($_GET['brand_id']);
		$dis_id = intval($_GET['dis_id']);
		
		$where['product.display'] = 1;
	
		$where['product_items.language_id'] = C('language_id');
		$order = 'product.id ASC';
	
		
		
		if($cat_id){
			$catIds = CategoryModel::getCategoryChildIds($cat_id);
			if($catIds){ 
				$where['catid'] = array('IN', $cat_id .','.$catIds);
			}else{
				$where['catid'] = $cat_id;
			}
		}
		if($brand_id)$where['brand_id'] = $brand_id;
		
		$product_db = D('product');
		$productList = $product_db->field('id,name,img')->join('product_items ON product_items.product_id = product.id')->where($where)->order($order)->select();

		if($productList){
			$result = array(
				'error' => 0,
				'content' => $productList,
			);
		}else{
			$result = array(
				'error' => 1,
				'content' => '该条件下不存在产品',
			);
		}
		echo json_encode($result);
	}
	
	public function goods_batch_ajax_by_id(){

		$produt_search_id = intval($_GET['produt_search_id']);
		
		$where['product.id'] = $produt_search_id;
		$where['product.display'] = 1;
	
		$where['product_items.language_id'] = C('language_id');
		$order = 'product.id ASC';
	
		
		$product_db = D('product');
		$productList = $product_db->field('id,name,img')->join('product_items ON product_items.product_id = product.id')->where($where)->order($order)->select();

		if($productList){
			$result = array(
				'error' => 0,
				'content' => $productList,
			);
		}else{
			$result = array(
				'error' => 1,
				'content' => '该条件下不存在产品',
			);
		}
		echo json_encode($result);	
	}
	
	public function add()
	{
		if(isset($_POST['dosubmit']))
		{
			$post = $_POST;
			$info = $this->upload(date('Y/m/d', time()));
			if(is_array($info)){
				//上传背景图片
				if($info){
				if (isset($_FILES['upimage']) && $_FILES['upimage']['name']){
					$post['bg_img'] = UPLOAD_PATH . $info['upimage']['savename'];
				}
				//上传面料图片
				if (isset($info['ml_img']) && $_FILES['ml_img']['name']){
					$post['ml_img'] = UPLOAD_PATH.$info['ml_img']['savename'];		
				}
				//上传商品列表

				if (isset($_FILES['goods_img']) && $_FILES['goods_img']['name']){
					$post['goods_img'] = UPLOAD_PATH . $info['goods_img']['savename'];
				}
			}else{
					$this->error($info);
			}}
			//上传面料图片到产品表
			$list_img = '';
			if(isset($post['focus_photo']) && $post['focus_photo']){
				$img = $post['focus_photo']; //原图
				$dir = dirname($img);
				$img_name = basename($img);
				$post['img'] = $img;
				$post['small_img'] = $dir . '/thumb_' . $img_name; //小图片
				$post['list_img']  = $dir . '/list_' . $img_name; //列表图片
			}			
			$pid = ProductModel::updateProductInfo($post);

			if(!$pid){
				$this->error('产品添加失败，请重新输入', U('product/add'));
			}
			//产品内容详细入库
			ProductModel::updateProductItems($post['product'], $pid);
			//其他分类入库
			$this->insert_category_product($pid, $post);
			//图片关联入库
			$this->insert_photo($pid, $post);
			//属性入库
			$this->insert_attribute_relation($pid, $post);
			
			//扩展分类入库
			$this->insert_product_other_cat($pid, $post);
			
			//产品关联
			$this->insert_product_relation($pid, $post);

			//图片关联背景展示图片入库
			$this->insert_background_photo($pid, $post);			
			
			$this->success('产品添加成功！', U('product/index'));
		
		}else{
			$productInfo = array();
			if(cookie('product_last_id')){
				$product_db = D('product');
				$product = $product_db->field('id,brand_id,catid,model_id')->where('id='.intval(cookie('product_last_id')))->find();

			}
			//下拉分类
			$select_categorys = CategoryModel::categorySelectList($product['catid']); 
			$this->assign('select_categorys', $select_categorys);
			//属性类型列表
			$modelList = AttributeModel::getModelList(); 
			$this->assign('modelList', $modelList);
			//品牌数组
			$brandList = array();
			$brands = CategoryModel::getCategoryListBase(CategoryModel::TYPE_BRAND);
			foreach ($brands as $cat){
				$brandList[$cat['id']] = $cat['name'];
			}
			$this->assign('brandList', $brandList);
			//其他分类列表
			$vocabularyList = array();
			$otherCategoryList = array();
			$vocabularyList = CategoryModel::getVocabularyList();
			foreach ($vocabularyList as $vocid => $voc_name){
				if($vocid<5){
					unset($vocabularyList[$vocid]);
					continue;
				}
				$otherCategoryList[$vocid] = CategoryModel::getCategoryListBase($vocid);
			}
			
			//关联属性
			$goods_attr_html = $this->get_attribute_ajax($is_ajax = 0, $productInfo['model_id'], $productInfo['id']);
			$this->assign('goods_attr_html', $goods_attr_html);
			
			//会员等级
			$rankList = UserModel::getRankList();
			$this->assign('rankList', $rankList);
			
			//供货商
			$suppliersList = SuppliersModel::getSuppliersList();
			$this->assign('suppliersList', $suppliersList);
			
			$this->assign('vocabularyList', $vocabularyList);
			$this->assign('otherCategoryList', $otherCategoryList);
			
			//设计师列表
			$designerList = UserModel::getUserDesignerList();
			$this->assign('designerList', $designerList);
			
			//产品颜色
			$product_colour = CategoryModel::getCategoryList(11);
			$this->assign('product_colour', $product_colour);	

			$product['style'] = 'display:none;';
			$this->assign('product', $product);	
			$this->display('product_form');
		}
	}
	
	public function edit()
	{
		$product_db = D('product');
		$pid = intval($_GET['pid']);
		$product = ProductModel::getProductInfo($pid);
		if(!$product){
			$this->error('您编辑的产品不存在！', U('product/index'));
		}
		if(isset($_POST['dosubmit']))
		{
			$post = $_POST;
		$info = $this->upload(date('Y/m/d', time()));
		if(is_array($info)){
			//修改背景图片
			if (isset($_FILES['upimage']) && $_FILES['upimage']['tmp_name']){
				$post['bg_img'] = UPLOAD_PATH . $info['upimage']['savename'];
			}
			//上传面料图片
			if (isset($info['ml_img']) && $_FILES['ml_img']['name']){
				$post['ml_img'] = UPLOAD_PATH.$info['ml_img']['savename'];		
			}
			//上传商品列表
			if (isset($_FILES['goods_img']) && $_FILES['goods_img']['name']){
				$post['goods_img'] = UPLOAD_PATH . $info['goods_img']['savename'];
			}
		}
			
			//上传图片到产品表
			$list_img = '';
			if(isset($post['focus_photo']) && $post['focus_photo']){
				$img = $post['focus_photo']; //原图
				$dir = dirname($img);
				$img_name = basename($img);
				$post['img'] = $img;
				$post['small_img'] = $dir . '/thumb_' . $img_name; //小图片
				$post['list_img']  = $dir . '/list_' . $img_name; //列表图片
			}
			
			$show_attr_array=array();
			foreach($_POST['show_attr_ids'] as $vs){
				$show_type = substr($vs,0,1);
				if($show_type==2){
					array_push($show_attr_array,substr($vs,2));
				}
			}
			$post['show_attr_ids'] = count($show_attr_array)>0?implode(",",$show_attr_array):"";
		
			$pid = ProductModel::updateProductInfo($post, $pid);
			if(!$pid){
				$this->error('产品编辑失败，请重新输入', U('product/edit', array('pid' => $pid)));
			}
			
			//价格浮动
			$product_price_changes = D('product_price_changes');
			$info = $product_price_changes->where('product_id='.$pid)->find();
			$data2 = array(
				'sell_price' => floatval($post['sell_price2']),
				'custom_price' => floatval($post['custom_price2']),
				'advanced_price' => floatval($post['advanced_price2']),
			);
			//dump($data2);exit;
			if($info){
				$product_price_changes->where(array('product_id' => $pid))->save($data2);
			}else{
				$data2['product_id'] = $pid;
				$product_price_changes->add($data2);
			}
			
			//产品内容详细入库
			ProductModel::updateProductItems($post['product'], $pid);
			
			//其他分类入库
			$this->insert_category_product($pid, $post);
			//图片关联入库
			$this->insert_photo($pid, $post);
			//属性入库
			$this->insert_attribute_relation($pid, $post);
			
			//扩展分类入库
			$this->insert_product_other_cat($pid, $post);
			
			//批发入库
			if(intval($_POST['wholesale']['qty'][0])){
				$_POST['wholesale']['product_id'] = $pid;
				$wholesaleInfo = PromotionModel::getProductWholesaleInfo($pid);
				$_POST['wholesale']['product_name'] = $post['product'][C('language_id')]['name'];
				PromotionModel::updateWholesaleInfo($_POST['wholesale'], $wholesaleInfo ? $wholesaleInfo['id'] : null);
			}else{
				PromotionModel::deleteProductWholesaleInfo($pid);
			}

			//图片关联背景展示图片入库
			$this->insert_background_photo($pid, $post);	
			
			//产品关联
			$this->insert_product_relation($pid, $post);
			
			ProductModel::deleteProductCache($pid);
			$this->success('产品编辑成功！', U('product/index'));
		}else{
			$product['items'] = ProductModel::getProductItems($pid);
			$this->assign('product', $product);
			
			//下拉分类
			$select_categorys = CategoryModel::categorySelectList($product['catid']); 
			$this->assign('select_categorys', $select_categorys);
			//属性类型列表
			$modelList = AttributeModel::getModelList(); 
			$this->assign('modelList', $modelList);
			//品牌数组
			$brandList = array();
			$brands = CategoryModel::getCategoryListBase(CategoryModel::TYPE_BRAND);
			foreach ($brands as $cat){
				$brandList[$cat['id']] = $cat['name'];
			}
			$this->assign('brandList', $brandList);
			//其他分类列表
			$vocabularyList = array();
			$otherCategoryList = array();
			$vocabularyList = CategoryModel::getVocabularyList();
			foreach ($vocabularyList as $vocid => $voc_name){
				if($vocid<5){
					unset($vocabularyList[$vocid]);
					continue;
				}
				$otherCategoryList[$vocid] = CategoryModel::getCategoryListBase($vocid);
			}
			$this->assign('vocabularyList', $vocabularyList);
			$this->assign('otherCategoryList', $otherCategoryList);
			
			//关联其他分类
			$otherCategoryIds = array();
			$category_product_db = D('category_product');
			$categorys = $category_product_db->field('catid')->where('pid='.$pid)->select();
			foreach ($categorys as $cat){
				$otherCategoryIds[] = $cat['catid'];
			}
			$this->assign('otherCategoryIds', $otherCategoryIds);
			//关联图片
			$product_photo_ids = '';
			$photoList = ProductModel::getProductPhotoList($pid);
			if($photoList){
				foreach ($photoList as $file){
					$product_photo_ids .= $file['fid'].',';
				}
			}
			$this->assign('product_photo_ids', $product_photo_ids);
			$this->assign('photoList', $photoList);

			//关联属性
			$goods_attr_html = $this->get_attribute_ajax($is_ajax = 0, $product['model_id'], $pid);
			$this->assign('goods_attr_html', $goods_attr_html);
			
			//扩展分类
			$other_cat_list = array();
			$otherCatIds = ProductModel::getOtherCatids($pid);
			if($otherCatIds){
				foreach ($otherCatIds as $catid){
					$other_cat_list[] = CategoryModel::categorySelectList($catid);
				}
			}
			$this->assign('other_cat_list', $other_cat_list);
			
			//属性分类列表
			$catdb = D('category');
			$catInfo = $catdb->where('id='.$product['catid'])->find();
			if($catInfo){
				if($catInfo['parentid']>0){
					$catInfo2 = $catdb->where('id='.$catInfo['parentid'])->find();
					$category_id = explode(",",$catInfo2['category_id']);
					$this->assign('category_id', $category_id);
				}else{
					$category_id = explode(",",$catInfo['category_id']);
					$this->assign('category_id', $category_id);
				}
			}
			$pcategory_id = explode(",",$product['category_id']);
			$this->assign('pcategory_id', $pcategory_id);
			
			//属性分类（颜色）列表
			$catdb = D('category');
			$catInfo = $catdb->where('id='.$product['catid'])->find();
			if($catInfo){
				if($catInfo['parentid']>0){
					$catInfo2 = $catdb->where('id='.$catInfo['parentid'])->find();
					$colour_id = explode(",",$catInfo2['colour_id']);
					$this->assign('colour_id', $colour_id);
				}else{
					$colour_id = explode(",",$catInfo['colour_id']);
					$this->assign('colour_id', $colour_id);
				}
			}
			$pcolour_id = explode(",",$product['colour_id']);
			$this->assign('pcolour_id', $pcolour_id);
			
			//批发信息
			$wholesale = PromotionModel::getProductWholesaleInfo($pid);
			$this->assign('wholesale', $wholesale);
			
			//尺码信息
			$size = PromotionModel::getProductSizeInfo($pid);
			$this->assign('size', $size);
			
			//会员等级
			$rankList = UserModel::getRankList();
			$this->assign('rankList', $rankList);
			//供货商
			$suppliersList = SuppliersModel::getSuppliersList();
			$this->assign('suppliersList', $suppliersList);
			
			//关联商品
			$productsRelatedList = ProductModel::getRelatedProductList($pid);
			$this->assign('productsRelatedList', $productsRelatedList);
			
			//设计师列表
			$designerList = UserModel::getUserDesignerList();
			$this->assign('designerList', $designerList);
			
			if($product['designer_id']){
				$designerProductList = ProductModel::getDesignerProductSelectList($product['designer_id']);
				$this->assign('designerProductList', $designerProductList);
			}

			//产品颜色
			$product_colour = CategoryModel::getCategoryList(11);
			$this->assign('product_colour', $product_colour);
			$product_colour_id = explode(",",$product['product_colour_id']);
			$this->assign('product_colour_id', $product_colour_id);

			//产品背景展示图片
			$product_background_photo_ids = '';
			$photoBackgroundList = ProductModel::getProductPhotoBackgroundList($pid);
			foreach ($photoBackgroundList as $file){
				$product_background_photo_ids .= $file['fid'].',';
			}
			$this->assign('product_background_photo_ids', $product_background_photo_ids);
			$this->assign('photoBackgroundList', $photoBackgroundList);
            
			$this->display('product_form');
		}
	}
	
	//删除产品
	public function delete()
	{
		$pid = intval($_GET['pid']);
		$product = ProductModel::getProductInfo($pid);
		if(!$product){
			$this->error('产品不存在！', U('product/index'));
		}
		ProductModel::deleteProductInfo($pid);
		$this->error('产品删除成功！', U('product/index'));
	}
	
	
	//回收站列表
	public function product_trach()
	{
		$product_db = M('product');
		
		if($_POST['dosubmit']){
			$pids = $_POST['pids'];
			$type = trim($_POST['type']);
			$pids = array_filter($pids);
			if($pids && $type)
			{
				foreach ($pids as $pid){
					if($type == 'back'){
						$product_db->where('id='.$pid)->save(array('is_delete' => 0,"display"=>0));
						ProductModel::deleteProductCache($pid);
					}else{ 
						ProductModel::deleteProductInfo($pid);
					}
				}
			}
			$this->success('操作成功', U('product/product_trach'));
		}
		
		$where = array(
			'is_delete' => 1,
		);
		
		$pageRows = 20;
		if(isset($_REQUEST['pageRows']) && intval($_REQUEST['pageRows'])){
			$pageRows = intval($_REQUEST['pageRows']);
		}
		
		//分页
		$product_db->where($where);
		$count = $product_db->count();//总记录数
		import("ORG.Util.Page");// 导入分页类
		$Page = new Page($count, $pageRows);// 实例化分页类 传入总记录数和每页显示的记录数
		$pageShow = $Page->show();// 分页显示输出
		$this->assign('pageShow', $pageShow);
		
		$where['language_id'] = C('language_id');
		//产品列表
//		$product_db->field('product.id');
		$product_db->field('product.id,product.sn,pri.name,product.sell_price,product.display,product.market_price,product.small_img,product.suppliers_id');
		$product_db->join('product_items AS pri ON product.id=pri.product_id');
		$product_db->order('product.id DESC');
		$product_db->limit($Page->firstRow.','.$Page->listRows);
		$product_db->where($where);
		$productList = $product_db->select();
		$this->assign('productList', $productList);
		$this->display('product_trach');
	}
	
	//添加商品到加收站
	public function product_trach_add()//beach_select_edit
	{
		$pid = intval($_GET['pid']);
		$product = ProductModel::getProductInfo($pid);
		if(!$product){
			$this->error('产品不存在！', U('product/index'));
		}
		$product_db = D('product');
		$product_db->where('id='.$pid)->save(array('is_delete' => 1));
		ProductModel::deleteProductCache($pid);
		
		//删除购物车的产品
		$where = array(
			'pid' => is_array($pid) ? array('IN', join(',', $pid)) : $pid,
		);
		$cart_db = D('cart_products');
		$cart_db->where($where)->delete();
		
		$this->success('成功添加商品到加收站！', U('product/index'));
	}
	
	//回收站商品还原到商品列表
	public function product_trach_back()
	{
		$pid = intval($_GET['pid']);
		$product_db = D('product');
		$product_db->where('id='.$pid)->save(array('is_delete' => 0,"display"=>0));
		ProductModel::deleteProductCache($pid);
		$this->success('该商品已还原到商品列表！请编辑该商品', U('product/edit',array("pid"=>$pid)));
	}
	
	//回收站删除产品
	public function product_trach_delete()
	{
		$pid = intval($_GET['pid']);
		$product = ProductModel::getProductInfo($pid);
		if(!$product){
			$this->error('产品不存在！', U('product/product_trach'));
		}
		ProductModel::deleteProductInfo($pid);
		$this->error('产品删除成功！', U('product/product_trach'));
	}
	
	
	
	/**
	 * 产品扩展分类关联入库
	 * @param int $pid 产品ID
	 * @param array $post post表单
	 */
	private function insert_category_product($pid, $post)
	{
		if(isset($post['category_product']) && $post['category_product']){
			$category_product_db = D('category_product');
			ProductModel::deleteProductCategoryRelation($pid); //删除产品关联分类
			if(is_array($post['category_product']) && count($post['category_product'])>0){
				foreach ($post['category_product'] as $catid){
					$data = array(
						'catid' => $catid,
						'pid' => $pid,
					);
					$category_product_db->add($data);
				}
			}
		}
	}
	
/**
	 * 产品扩展分类关联入库
	 * @param int $pid 产品ID
	 * @param array $post post表单
	 */
	private function insert_product_other_cat($pid, $post)
	{
		if(isset($post['other_cat']) && $post['other_cat']){
			$product_other_cat_db = D('product_other_cat');
			$product_other_cat_db->where('pid='.$pid)->delete(); //删除产品关联分类
			if(is_array($post['other_cat']) && count($post['other_cat'])>0){
				foreach ($post['other_cat'] as $catid){
					if($catid==0)continue;
					$data = array(
						'catid' => $catid,
						'pid' => $pid,
					);
					$product_other_cat_db->add($data);
				}
			}
		}
	}
	
	/**
	 * 产品图片关联入库
	 * @param int $pid 产品ID
	 * @param array $post post表单
	 */
	private function insert_photo($pid, $post)
	{
		$photo_ids = $post['photo_name'];
		if($photo_ids){
			$photo_ids = rtrim($photo_ids,',');
			$fids = explode(',', $photo_ids);
			if(count($fids)){
				ProductModel::deleteProductPhotoRelation($pid); //删除关联图片
				foreach ($fids as $fid){
					$data = array(
						'fid' => $fid,
						'pid' => $pid,
					);
					$product_photo_relation_db = D('product_photo_relation');
					$product_photo_relation_db->add($data);
				}
			}
		}else{
			ProductModel::deleteProductPhotoRelation($pid); //删除关联图片
		}
	}

	/**
	 * 产品图片关联入库
	 * @param int $pid 产品ID
	 * @param array $post post表单
	 */
	private function insert_background_photo($pid, $post)
	{
		$product_background_photo_db = D('product_background_photo');		
		$photo_ids = $post['photo_name_bj'];
		if($photo_ids){
			$photo_ids = rtrim($photo_ids,',');
			$fids = explode(',', $photo_ids);
			foreach ($fids as $fid){
				if(!$fid) continue;
				$data = array(
					'pid' => $pid,
				);
				$product_background_photo_db->where(array('fid'=>$fid))->save($data);
			}
		}
		$photo_ids = $post['del_photo_name_bj'];
		if($photo_ids){
			$photo_ids = rtrim($photo_ids,',');
			$fids = explode(',', $photo_ids);
			foreach ($fids as $fid){
				if(!$fid) continue;
				$product_background_photo_db->where(array('fid'=>$fid))->delete();
			}
		}			
	}
	
	/**
	 * 产品属性关联入库
	 * @param int $pid 产品ID
	 * @param array $post post表单
	 */
	private function insert_attribute_relation($pid, $post)
	{
    	$product_attribute_db = D('product_attribute');
		$model_id = intval($post['model_id']);
		$attributeList = AttributeModel::getAttributeList($model_id); // 属性列表
		ProductModel::deleteProductAttributeRelation($pid); //删除产品关联属性
    	foreach ($attributeList as $attr){
			$post_field = $post['field_'.$attr['attr_id']]; //属性post字段
//			dump($post_field);exit;
			if(isset($post_field) && $post_field){
				 //下拉单选
				if(is_numeric($post_field))
				{
					$data = array(
						'product_id' => $pid,
						'attr_id' => $attr['attr_id'],
						'attr_value_id' => $post_field,
					);
					$product_attribute_db->add($data);
				}
				 //单选
				elseif(is_string($post_field))
				{
					$data = array(
						'product_id' => $pid,
						'attr_id' => $attr['attr_id'],
						'attr_value' => $post_field,
					);
					$product_attribute_db->add($data);
				}
				//复选
				elseif(is_array($post_field) && count($post_field)>0)
				{ 
					$is_default = 0;
					$attr_value_id = 0;
					$attr_value = '';
					//默认值
					if(isset($post_field['default'])){
						//more option 支持多选中
						if(in_array($attr['attr_id'],array(54,70,112,134))){
                            $defaultArr = explode(',', $post_field['default']);
						}else{
						    $is_default = $post_field['default'] ? intval($post_field['default']) : 0;
						}
						unset($post_field['default']);
					}
					
					foreach ($post_field as $post_key => $post_value )
					{
						if($attr['attr_input_type']==1 && $post_value){
							$attr_value_id = intval($post_value);
							if($is_default==0 && $post_key==0){
								$is_default = $attr_value_id;
							}
						}
						elseif($attr['attr_input_type']==0 && $post_value){
							$attr_value = trim($post_value);
						}
                        
                        //more option 支持多选中
                        if(in_array($attr['attr_id'],array(54,70,112,134))){
                            $is_default_id = in_array($attr_value_id, $defaultArr) ? $attr_value_id : 0; 
                        }else{
                            $is_default_id = $attr_value_id==$is_default ? $is_default : 0;                       	
                        }

						$data = array(
							'product_id' => $pid,
							'attr_id' => $attr['attr_id'],
							'attr_value_id' => $attr_value_id,
							'attr_value' => $attr_value,
							'is_default' => $is_default_id,
						);
						$product_attribute_db->add($data);
						//echo $product_attribute_db->getLastSql()."<br>";
					}
				}
			}
		}
		//exit;
	}
	
	//添加产品关联
	private function insert_product_relation($pid, $post)
	{
		$related_info = array();
   	if($post['related_info'] != '{}') {
    	$related_info = strtr(stripcslashes($post['related_info']), '\'', '"');
      $related_info = json_decode($related_info);
    }
     ProductModel::updateProductRelated($pid, $related_info);
	}
	
	//产品设置
	public function config()
	{
		$config = SiteModel::getShopConfigList();
		if(isset($_POST['dosubmit'])){
			unset($_POST['dosubmit']);
			//上传水印图片
			if (isset($_FILES['upimage']) && $_FILES['upimage']['tmp_name']){
				import('ORG.Util.Image');
				$imageInfo = Image::getImageInfo($_FILES['upimage']['tmp_name']);
				if($imageInfo){
					$water = ROOT_PATH.'/data/water.'.$imageInfo['type'];
					if(move_uploaded_file($_FILES['upimage']['tmp_name'], $water)){
						$_POST['water_img'] = '/data/water.'.$imageInfo['type'];
					}
				}
			}
			
			$_POST['water_alpha'] = intval($_POST['water_alpha']);
			
			SiteModel::updateShopConfig($_POST);
			$this->success('保存成功', U('product/config'));
		}else{
			$this->assign('config', $config);
		  $this->display('config');
		}
	}
	
	/**
	 * 获取属性html展示
	 * @param int $is_ajax 是否ajax调用1.是,0.否
	 * @param int $model_id 类型ID
	 * @param int $pid 产品ID
	 */
	 public function get_attribute_ajax($is_ajax = 0, $model_id, $pid = null, $did=0)
	 {
	 	 $modelList = AttributeModel::getModelList();
	 	 if(!$modelInfo = $modelList[$model_id]){
	 	 		if($is_ajax){
	 	 			 exit('');
	 	 		}else{
	 	 			return '';
	 	 		}
	 	 }

	 	 $product_attributes_array = null;
		 if($did){
		 	$designer_product_db = D('designer_product');
			$count = $designer_product_db->where('id='.$did)->count();
			if($count==0){
				if($is_ajax){
					 exit('');
				}else{
					return '';
				}
			}
			$goods_attr_html = AttributeModel::getAttributeValuesHtml($model_id, $pid, $did);
		 }else{
		 	if($pid){
				$product_db = D('product');
				$count = $product_db->where('id='.$pid)->count();
				if($count==0){
					if($is_ajax){
						 exit('');
					}else{
						return '';
					}
				}
			 }
			 $goods_attr_html = AttributeModel::getAttributeValuesHtml($model_id, $pid);
		 }

	 	 
 			if($is_ajax){
 	 			echo $goods_attr_html;
 	 		}else{
 	 			return $goods_attr_html;
 	 		}
	 	 
	 }
	//下拉分类返回属性类型ID;
	public function select_model_ajax()
	{
		$catid = intval($_GET['catid']);
		$cat_db = D('category');
		$model_id = $cat_db->where(array('id' => $catid))->getField('model_id');
		$modelList = AttributeModel::getModelList();
		if($modelList[$model_id]){
			exit($model_id) ;
		}else{
			exit('0');
		}
	}
	
	//商品类型;
	public function attribute_type_ajax()
	{
		$type = intval($_GET['type']);
		$modeldb = D('model');
		$modelInfo = $modeldb->find($type);
		if($modelInfo['type']){
			exit($modelInfo['type']) ;
		}else{
			exit('0');
		}
	}
	
	//swfupload上传图片
	public function swfupload_ajax()
	{
		$subdir = '';
		if($_REQUEST['type'] == 'comment'){
			$subdir = 'comment/';
		}
		if($_REQUEST['type'] == 'orders_pay_return'){
			$subdir = 'orders_pay_return/';
		}
		if($_REQUEST['type'] == 'product_background_photo'){
			$subdir = '';
		}					
		$subdir .= date('Y/m/d/', time());
		import("ORG.Net.UploadFile");
		$upload = new UploadFile();// 实例化上传类
		$upload->maxSize  = C('UPLOAD_SIZE') ;// 设置附件上传大小
		$upload->allowExts  = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
		$upload->savePath =  '.'.UPLOAD_PATH;// 设置附件上传目录
		$upload->autoSub = true;//开启子目录
		$upload->subType = 'custom';// 子目录创建方式 可以使用hash date custom
		$upload->subDir = $subdir;
		$upload->thumb = true;//开启缩略图
		$upload->thumbType = C('product_thumb_type') ? intval(C('product_thumb_type')) : 0;
		$upload->thumbMaxWidth = C('product_list_width').','.C('product_thumb_width').',250';
		$upload->thumbMaxHeight = C('product_list_height').','.C('product_thumb_height').',250';
		//$upload->thumbMaxWidth = C('product_thumb_width');
//		$upload->thumbMaxHeight = C('product_thumb_height');
//		$upload->thumbPrefix = 'thumb_';
		$upload->thumbPrefix = 'list_,thumb_,250x250_';
		if(!$upload->upload()) {// 上传错误提示错误信息
			echo $upload->getErrorMsg();
		}else{// 上传成功 获取上传文件信息
		    $photo_db = D('product_photo');
		    if($_REQUEST['type'] == 'comment'){
			    $photo_db = D('comment_photo');
			}
		    if($_REQUEST['type'] == 'orders_pay_return'){
			    $photo_db = D('orders_pay_return_photo');
			}
		    if($_REQUEST['type'] == 'product_background_photo'){
			    $photo_db = D('product_background_photo');
			}							
			$photoArray = array();
			$files = $upload->getUploadFileInfo();
			foreach ($files as $file){
				$img = $file['savename'];
				$thumb = 'thumb_'.basename($img);
				$data['img'] = UPLOAD_PATH.$img;
				$data['thumb'] = UPLOAD_PATH.$subdir.$thumb;
				$insertId = $photo_db->add($data);
				if($insertId){
//					if(is_file(ROOT_PATH.C('water_img')) && C('water_place')){
//						import('ORG.Util.Image');
//						Image::water(ROOT_PATH.UPLOAD_PATH.$img, ROOT_PATH.C('water_img'), C('water_place'), null , C('water_alpha'));
//					}
					echo UPLOAD_PATH.$subdir.$thumb.'|'.UPLOAD_PATH.$subdir.$thumb.'|'.UPLOAD_PATH.$img.'|'.$insertId;exit;
				}else{
					exit('0');
				}
			}
	 	}
	}
	
	//修改产品排序
	public function change_listorder_ajax()
	{
		$pid = intval($_GET['pid']);
		$listorder = intval($_GET['listorder']);
		$product_db = D('product');
		$product_db->where('id='.$pid)->save(array('listorder' => $listorder));
		ProductModel::deleteProductCache($pid);
	}
	
	//修改产品状态
	public function change_status_ajax()
	{
		$pid = intval($_GET['pid']);
		$display = intval($_GET['display']);
		$product_db = D('product');
		$product_db->where('id='.$pid)->save(array('display' => $display));
		ProductModel::deleteProductCache($pid);
		//设置产品所使用面料的上下架时间
		SuppliersModel::suppliersUpDown($pid,$display);	
		//到货通知邮件
		if($display == 1) $this->notifyMeEmail($pid);
	}
	
	//修改作品状态
	public function change_status_ajax02()
	{
		$pid = intval($_GET['pid']);
		$display = intval($_GET['display']);
		$designer_product_db = D('designer_product');
		$designer_product_db->where('id='.$pid)->save(array('display' => $display));
	}
	
	//查看图片链接
	public function public_show_photo_link_ajax()
	{
		$img = $_GET['img'];
		if(empty($img)){
			return false;
		}else{
			$dir = dirname($img);
			$name = basename($img);
			$data = array(
				'img' => $img,
				'list_img' => $dir.'/list_'.$name,
				'small_img' => $dir.'/thumb_'.$name,
			);
			$this->assign($data);
			$this->display('show_photo_link');
		}
	}

	//商品关联列表
	public function productrelated_list($pid)
	{
		$productCount = ProductModel::getRelatedProductCount($pid);
		import("ORG.Util.Page");// 导入分页类
		$Page = new Page($productCount, 20);// 实例化分页类 传入总记录数和每页显示的记录数
		$pageShow = $Page->show();// 分页显示输出
		$this->assign('pageShow', $pageShow);
		
		$productList = ProductModel::getRelatedProductList($pid, $Page->firstRow, $Page->listRows);
		$this->assign('productList', $productList);
		$this->display('productrelated_list');
	}
	//商品关联
	public function productrelated_add()
	{
		$language_id = C('language_id');
		$product_db = D('product');
		
			$where = array(
				'product.is_delete' => 0,
				'product_items.language_id' => $language_id,
		);
		if(isset($_REQUEST) && $_REQUEST)
		{
			if(isset($_REQUEST['product_name']) && trim($_REQUEST['product_name'])){
				$where['product_items.name'] = array('like', '%'.trim($_REQUEST['product_name']).'%');
			}
			if(isset($_REQUEST['product_sn']) && trim($_REQUEST['product_sn'])){
				$where['product.sn'] = array('like', '%'.trim($_REQUEST['product_sn']).'%');;
			}
			//搜索分类
			if(isset($_REQUEST['catid']) && intval($_REQUEST['catid'])){
				$catid = intval($_POST['catid']);
				$where['product.catid'] = $catid;
			}
			//搜索产品类型
			if(isset($_REQUEST['model_id']) && intval($_REQUEST['model_id'])){
				$where['product.model_id'] = intval($_REQUEST['model_id']);
			}
		}
		$product_db->join('product_items oN product_items.product_id=product.id');
		$productCount = $product_db->where($where)->count();

		import("ORG.Util.Page");// 导入分页类
		$Page = new Page($productCount, 12);// 实例化分页类 传入总记录数和每页显示的记录数
		$pageShow = $Page->show();// 分页显示输出
		$this->assign('pageShow', $pageShow);
		
		$product_db->field('product.id AS pid,product_items.name');
		$product_db->join('product_items ON product_items.product_id=product.id');
		$product_db->where($where);
		$product_db->limit($Page->firstRow, $Page->listRows);
		$productList = $product_db->select();
		$this->assign('productList', $productList);
		$this->display('productrelated_list');
	}
	//商品关联搜索
	public function productrelated_select()
	{
		$select_categorys = CategoryModel::categorySelectList($catid); 
		$this->assign('select_categorys', $select_categorys);
		//属性类型列表
		$modelList = AttributeModel::getModelList(); 
		$this->assign('modelList', $modelList);
		$this->display('productrelated_select');
	}
	
	//设计师作品列表
	public function product_designer_list()
	{
		$user_designer_product = D('user_designer_product udp');
		$where = array();
		
		if(isset($_REQUEST) && $_REQUEST)
		{
			if(isset($_REQUEST['keyword']) && trim($_REQUEST['keyword'])){
				$where['udp.designer_name'] = array('like', '%'.trim($_REQUEST['keyword']).'%');
			}
			if(isset($_REQUEST['designer_id']) && $_REQUEST['designer_id'] != -1){
				$where['udp.designer_id'] = intval($_REQUEST['designer_id']);
			}
		}
		
		$productCount = $user_designer_product->where($where)->count();

		import("ORG.Util.Page");// 导入分页类
		$Page = new Page($productCount, 20);// 实例化分页类 传入总记录数和每页显示的记录数
		$pageShow = $Page->show();// 分页显示输出
		$this->assign('pageShow', $pageShow);
		
		$user_designer_product->field('udp.designer_product_id,users.username,udp.display,udp.small_img,udp.start_time,udp.product_up,udp.product_down,udp.designer_name');
		$user_designer_product->join('users ON users.id = udp.designer_id');
		$user_designer_product->where($where);
		$user_designer_product->limit($Page->firstRow, $Page->listRows);
		$productList = $user_designer_product->select();
//		echo $user_designer_product->getLastSql();exit;
//		dump($productList);exit;
		$this->assign('productList', $productList);
		$this->assign('search', $_REQUEST);
		//设计师列表
		$designerList = UserModel::getUserDesignerList();
		$this->assign('designerList', $designerList);
		
		$this->display('product_designer_list');
	}
	
	//设计师作品详细
	public function product_designer_info()
	{
		$designer_product_id = intval($_REQUEST['did']);
		if($designer_product_id){
			$product = ProductModel::getUserDesignerProductInfo($designer_product_id);
		}
		if(isset($_POST['dosubmit']))
		{
			$post = $_POST;
			
		//上传背景图片
			if (isset($_FILES['upimage']) && $_FILES['upimage']['tmp_name']){
				$info = $this->upload(date('Y/m/d/', time()));
				if(is_array($info)) {// 上传成功 获取上传文件信息
					$post['bg_img'] = UPLOAD_PATH . $info['upimage']['savename'];
				}else{
					$this->error($info);
				}
			}
			
			//上传图片到产品表
			if(isset($post['focus_photo']) && $post['focus_photo']){
				$img = $post['focus_photo']; //原图
				$dir = dirname($img);
				$img_name = basename($img);
				$post['img'] = $img;
				$post['small_img'] = $dir . '/thumb_' . $img_name; //小图片
				$post['list_img'] = $dir . '/list_' . $img_name; //列表图片
			}
			
			$post['attr'] = $this->get_designer_attribute_relation($post);
			
			$pid = ProductModel::updateUserDesignerProductInfo($post, $designer_product_id);
			if(!$pid){
				$this->error('作品编辑失败', U('product/product_designer_list'));
			}
			//图片关联入库
			$photo_ids = $post['photo_name'];
			$user_designer_photo_relation_db = D('user_designer_photo_relation');
			if($photo_ids){
				$photo_ids = rtrim($photo_ids,',');
				$fids = explode(',', $photo_ids);
				if(count($fids)){
					$user_designer_photo_relation_db->where('pid='.$pid)->delete(); //删除关联图片
					foreach ($fids as $fid){
						$data = array(
							'fid' => $fid,
							'pid' => $pid,
						);
						$user_designer_photo_relation_db->add($data);
					}
				}
			}
			$this->success('作品编辑成功', U('product/product_designer_list'));
		}else{
			if($designer_product_id){
				$photoList = ProductModel::getUserDesignerProductPhotoList($designer_product_id);
				
			}
			//关联属性
				$goods_attr_html = $this->get_designer_attribute_ajax($is_ajax = 0, 1, $designer_product_id);
				$this->assign('goods_attr_html', $goods_attr_html);
			$modelList = AttributeModel::getModelList();
			$this->assign('modelList', isset($modelList) ? $modelList : array());
			
			$this->assign('product', isset($product) ? $product : array());
			$this->assign('photoList', isset($photoList) ? $photoList : array());
			//设计师列表
			$designerList = UserModel::getUserDesignerList();
			$this->assign('designerList', $designerList);
			$this->display('product_designer_info');
		}
	}
	
	/**
	 * 获取作品属性html展示
	 * @param int $is_ajax 是否ajax调用1.是,0.否
	 * @param int $model_id 类型ID
	 * @param int $pid 产品ID
	 */
	 public function get_designer_attribute_ajax($is_ajax = 0, $model_id, $pid = null)
	 {
	 	 $modelList = AttributeModel::getModelList();
	 	 if(!$modelInfo = $modelList[$model_id]){
	 	 		if($is_ajax){
	 	 			 exit('');
	 	 		}else{
	 	 			return '';
	 	 		}
	 	 }

	 	 $goods_attr_html = AttributeModel::getDesignerAttributeValuesHtml($model_id, $pid);
 			if($is_ajax){
 	 			echo $goods_attr_html;
 	 		}else{
 	 			return $goods_attr_html;
 	 		}
	 }
/**
	 * 作品属性关联
	 * @param array $post post表单
	 */
	private function get_designer_attribute_relation($post)
	{
		$data = array();
			$model_id = intval($post['model_id']);
			$attributeList = AttributeModel::getAttributeList($model_id, array('attr_designer' => 1)); // 属性列表
			if($attributeList){
	    	foreach ($attributeList as $attr){
				$post_field = $post['field_'.$attr['attr_id']]; //属性post字段
				if(isset($post_field) && $post_field)
				{
					$is_default = 0;
					$attr_value_id = 0;
					$attr_value = '';
					//默认值
					if(isset($post_field['default'])){
						$is_default = $post_field['default'] ? intval($post_field['default']) : 0;
						unset($post_field['default']);
					}
					
					foreach ($post_field as $post_key => $post_value )
					{
						if($attr['attr_input_type']==1 && $post_value){
							$attr_value_id = intval($post_value);
							if($is_default==0 && $post_key==0){
								$is_default = $attr_value_id;
							}
						}
						elseif($attr['attr_input_type']==0 && $post_value){
							$attr_value = trim($post_value);
						}
	
						$data[] = array(
							'attr_id' => $attr['attr_id'],
							'attr_value_id' => $attr_value_id,
							'attr_value' => $attr_value,
							'is_default' => $attr_value_id==$is_default ? $is_default : 0,
						);
					}
				}
    	}
		}
		return $data ? $data : null;
	}
	
	public function select_designer_product_ajax()
	{
		$designer_id = intval($_REQUEST['did']);
		$productList = ProductModel::getDesignerProductSelectList($designer_id);
		
		echo json_encode($productList);
	}
	
	//尺码对照表
	public function product_size_list()
	{
		$product_user_size = D('product_user_size');
		$where = array();
		
		/*if(isset($_REQUEST) && $_REQUEST)
		{
			if(isset($_REQUEST['keyword']) && trim($_REQUEST['keyword'])){
				$where['udp.designer_name'] = array('like', '%'.trim($_REQUEST['keyword']).'%');
			}
			if(isset($_REQUEST['designer_id']) && $_REQUEST['designer_id'] != -1){
				$where['udp.designer_id'] = intval($_REQUEST['designer_id']);
			}
		}*/
		
		$sizeCount = $product_user_size->where($where)->count();

		import("ORG.Util.Page");// 导入分页类
		$Page = new Page($sizeCount, 20);// 实例化分页类 传入总记录数和每页显示的记录数
		$pageShow = $Page->show();// 分页显示输出
		$this->assign('pageShow', $pageShow);
		
		$product_user_size->where($where);
		$product_user_size->limit($Page->firstRow, $Page->listRows);
		$sizeList = $product_user_size->select();
//		echo $user_designer_product->getLastSql();exit;
//		dump($productList);exit;
		$this->assign('sizeList', $sizeList);
		$this->assign('search', $_REQUEST);
		
		$this->display('product_size_list');
	}
	
	//添加尺码
	public function product_size_add()
	{
		if(isset($_POST['dosubmit']))
		{
			$post = $_POST;
			$product_user_size = D('product_user_size');
					
			$data = array(
				'height' 			=> $post['height'],
				'weight' 			=> $post['weight'],
				'age' 				=> $post['age'],
				'height2' 			=> $post['height2'],
				'weight2' 			=> $post['weight2'],
				'age2' 				=> $post['age2'],
				'circumference' 	=> $post['circumference'],
				'waistline' 		=> $post['waistline'],
				'hipline' 			=> $post['hipline'],
				'shoulder' 			=> $post['shoulder'],
				'forepart_length' 	=> $post['forepart_length'],
				'outside_sleeve' 	=> $post['outside_sleeve'],
				'time' 				=> time(),
			);
			
			$pid = $product_user_size->add($data);
			if(!$pid){
				$this->error('尺码添加失败，请重新输入', U('product/product_size_add'));
			}
			
			$this->success('尺码添加成功！', U('product/product_size_list'));
		
		}else{
			$this->display('product_size');
		}
	}
	
	//编辑尺码
	public function product_size_edit()
	{	
		$pid = intval($_REQUEST['id']);
		if(isset($_POST['dosubmit']))
		{
			if(!$pid){
				$this->error('尺码编辑失败，请重新输入');
			}
			
			$post = $_POST;
			$product_user_size = D('product_user_size');
					
			$data = array(
				'height' 			=> $post['height'],
				'weight' 			=> $post['weight'],
				'age' 				=> $post['age'],
				'height2' 			=> $post['height2'],
				'weight2' 			=> $post['weight2'],
				'age2' 				=> $post['age2'],
				'circumference' 	=> $post['circumference'],
				'waistline' 		=> $post['waistline'],
				'hipline' 			=> $post['hipline'],
				'shoulder' 			=> $post['shoulder'],
				'forepart_length' 	=> $post['forepart_length'],
				'outside_sleeve' 	=> $post['outside_sleeve'],
			);
			
			$product_user_size->where(array('id' => $pid))->save($data);
			
			
			$this->success('尺码编辑成功！', U('product/product_size_list'));
		
		}else{
		
			$product_user_size = D('product_user_size');
			$size = $product_user_size->find($pid);
			//echo $product_user_size->getLastSql();
		
			$this->assign('size', $size);
			$this->display('product_size');
		}
	}
	
	//删除尺码
	public function product_size_delete()
	{
		$pid = intval($_GET['id']);
		$product_user_size = D('product_user_size');
		$size = $product_user_size->find($pid);
		if(!$size){
			$this->error('尺码不存在！', U('product/product_size_list'));
		}
		
		$product_user_size->where('id='.$pid)->delete();
		$this->success('尺码删除成功！', U('product/product_size_list'));
	}
	
	//作品列表
	public function designer_product()
	{
		$designer_product_db = M('designer_product');
		
		$where = array(
			'product_id' => 0,
		);
		//$where['designer_id'] = array('gt', 0);
		
		$pageRows = 20;
		if(isset($_REQUEST['pageRows']) && intval($_REQUEST['pageRows'])){
			$pageRows = intval($_REQUEST['pageRows']);
		}
		
		//分页
		$designer_product_db->where($where);
		$count = $designer_product_db->count();//总记录数
		import("ORG.Util.Page");// 导入分页类
		$Page = new Page($count, $pageRows);// 实例化分页类 传入总记录数和每页显示的记录数
		$pageShow = $Page->show();// 分页显示输出
		$this->assign('pageShow', $pageShow);
		
		//作品列表
		$designer_product_db->order('id DESC');
		$designer_product_db->limit($Page->firstRow.','.$Page->listRows);
		$designer_product_db->where($where);
		$productList = $designer_product_db->select();
		$this->assign('productList', $productList);
		$this->display('designer_product');
	}
	
	//升级作品
	public function designer_product_edit()
	{
		$designer_product_db = D('designer_product');
		$pid = intval($_GET['pid']);
		$product_db = D('product');
		$product = $designer_product_db->where('id='.$pid)->find();
				
		if(!$product){
			$this->error('您升级的作品不存在！', U('product/designer_product'));
		}
		if(isset($_POST['dosubmit']))
		{
			$post = $_POST;
			
			//上传背景图片
			if (isset($_FILES['upimage']) && $_FILES['upimage']['tmp_name']){
				$info = $this->upload(date('Y/m/d/', time()));
				if(is_array($info)) {// 上传成功 获取上传文件信息
					$post['bg_img'] = UPLOAD_PATH . $info['upimage']['savename'];
				}else{
					$this->error($info);
				}
			}
			
			//上传图片到产品表
			$list_img = '';
			if(isset($post['focus_photo']) && $post['focus_photo']){
				$img = $post['focus_photo']; //原图
				$dir = dirname($img);
				$img_name = basename($img);
				$post['img'] = $img;
				$post['small_img'] = $dir . '/thumb_' . $img_name; //小图片
				$post['list_img']  = $dir . '/list_' . $img_name; //列表图片
			}
			
			
			$pid = ProductModel::updateProductInfo($post, $pid,$did=1);
			if(!$pid){
				$this->error('作品升级失败，请重新输入', U('product/designer_product_edit', array('pid' => $pid)));
			}
			//产品内容详细入库
			ProductModel::updateProductItems($post['product'], $pid);
			
			//其他分类入库
			$this->insert_category_product($pid, $post);
			//图片关联入库
			$this->insert_photo($pid, $post);
			//属性入库
			$this->insert_attribute_relation($pid, $post);
			
			//扩展分类入库
			$this->insert_product_other_cat($pid, $post);
			
			//批发入库
			if(intval($_POST['wholesale']['qty'][0])){
				$_POST['wholesale']['product_id'] = $pid;
				$wholesaleInfo = PromotionModel::getProductWholesaleInfo($pid);
				$_POST['wholesale']['product_name'] = $post['product'][C('language_id')]['name'];
				PromotionModel::updateWholesaleInfo($_POST['wholesale'], $wholesaleInfo ? $wholesaleInfo['id'] : null);
			}else{
				PromotionModel::deleteProductWholesaleInfo($pid);
			}
			
			//商品尺码入库
			if($_POST['size']['size'][0]){
				$_POST['size']['product_id'] = $pid;
				$sizeInfo = PromotionModel::getProductSizeInfo($pid);
				$_POST['size']['product_name'] = $post['product'][C('language_id')]['name'];
				PromotionModel::updateSizeInfo($_POST['size'], $sizeInfo ? $sizeInfo['id'] : null);
			}else{
				PromotionModel::deleteProductSizeInfo($pid);
			}
			
			//产品关联
			$this->insert_product_relation($pid, $post);
			
			$data2 = array(
				'product_id' => $pid,
			);
			$designer_product_db->where(array('id' => $product['id']))->save($data2);
			
			$this->success('作品升级成功！', U('product/designer_product'));
		}else{
			
			//下拉分类
			$select_categorys = CategoryModel::categorySelectList($product['catid']); 
			$this->assign('select_categorys', $select_categorys);
			//属性类型列表
			$modelList = AttributeModel::getModelList(); 
			$this->assign('modelList', $modelList);

			//其他分类列表
			$vocabularyList = array();
			$otherCategoryList = array();
			$vocabularyList = CategoryModel::getVocabularyList();
			foreach ($vocabularyList as $vocid => $voc_name){
				if($vocid<5){
					unset($vocabularyList[$vocid]);
					continue;
				}
				$otherCategoryList[$vocid] = CategoryModel::getCategoryListBase($vocid);
			}
			$this->assign('vocabularyList', $vocabularyList);
			$this->assign('otherCategoryList', $otherCategoryList);
			
			//关联其他分类
			$otherCategoryIds = array();
			$category_product_db = D('category_product');
			$categorys = $category_product_db->field('catid')->where('pid='.$pid)->select();
			foreach ($categorys as $cat){
				$otherCategoryIds[] = $cat['catid'];
			}
			$this->assign('otherCategoryIds', $otherCategoryIds);
			//关联图片
			$product_photo_ids = '';
			$photoList = ProductModel::getProductPhotoList($product['product_id'],$pid);
			if($photoList){
				foreach ($photoList as $file){
					$product_photo_ids .= $file['fid'].',';
				}
			}
			$this->assign('product_photo_ids', $product_photo_ids);
			$this->assign('photoList', $photoList);

			//关联属性
			$goods_attr_html = $this->get_attribute_ajax($is_ajax = 0, $product['model_id'], $product['product_id'], $pid);
			$this->assign('goods_attr_html', $goods_attr_html);
			
			//扩展分类
			$other_cat_list = array();
			$otherCatIds = ProductModel::getOtherCatids($pid);
			if($otherCatIds){
				foreach ($otherCatIds as $catid){
					$other_cat_list[] = CategoryModel::categorySelectList($catid);
				}
			}
			$this->assign('other_cat_list', $other_cat_list);
			
			//批发信息
			$wholesale = PromotionModel::getProductWholesaleInfo($pid);
			$this->assign('wholesale', $wholesale);
			
			//尺码信息
			$size = PromotionModel::getProductSizeInfo($pid);
			$this->assign('size', $size);
			
			//会员等级
			$rankList = UserModel::getRankList();
			$this->assign('rankList', $rankList);
			//供货商
			$suppliersList = SuppliersModel::getSuppliersList();
			$this->assign('suppliersList', $suppliersList);
			
			//关联商品
			$productsRelatedList = ProductModel::getRelatedProductList($pid);
			$this->assign('productsRelatedList', $productsRelatedList);
			
			//设计师列表
			$designerList = UserModel::getUserDesignerList();
			$this->assign('designerList', $designerList);
			
			if($product['designer_id']){
				$designerProductList = ProductModel::getDesignerProductSelectList($product['designer_id']);
				$this->assign('designerProductList', $designerProductList);
			}
			$this->assign('product', $product);
			$this->display('designer_product_edit');
		}
	}
	
	//删除作品
	public function designer_product_delete()
	{
		$pid = intval($_GET['pid']);
		$designer_product_db = D('designer_product');
		$product = $designer_product_db->find($pid);
		if(!$product){
			$this->error('作品不存在！', U('product/product_trach'));
		}
		//TODO没有删除图片
		$product_photo_relation_db = D('product_photo_relation');
		$product_photo_relation_db->where('did='.$pid)->delete();

		//删除产品关联属性
		$product_attribute_db = D('product_attribute');
		$product_attribute_db->where('dproduct_id='.$pid)->delete();
		
		$where = array(
			'id' => $pid,
		);
		$designer_product_db->where($where)->delete();
					
		$this->error('作品删除成功！', U('product/product_trach'));
	}

    //ajax修改sorts
	public function edit_sort_ajax()
	{
		$id = intval($_POST['id']);
		$val = intval($_POST['val']);
		
		$where = array('id' => $id);

		$product_db = D('product');
		$result = $product_db->where($where)->save(array('sorts'=>$val));
		
		echo $result;
	}
            
    public function user_size_list(){
        $list = M('user_size_items')->query('select height from user_size_items group by height');
        $this->assign('list',$list);
        $this->display();
    }
    public function user_size_list_1(){
        $height = $_GET['height'];
        $pageRows = 150;
        $db = M('user_size_items');
        $count = $db->where('height='.$height)->count();
        import("ORG.Util.Page");
        $Page = new Page($count,$pageRows);
        $pageShow = $Page->show();
        $list = $db->limit($Page->firstRow.','.$Page->listRows)->where('height='.$height)->order('weight')->select();
        $this->assign('list',$list);
        $this->assign('pageShow', $pageShow);
        $this->display();
    }
    public function user_size_add(){


       if(IS_POST){
                      $db =  M('user_size_items');
                      //var_dump($_POST);die;
            foreach($_POST['height'] as $k=>$v){
            if(empty($_POST['height'][$k]))
                continue;
                $data = array();
                $data['id'] = null;
                $data['weight'] = $_POST['weight'][$k];
                $data['height'] = $_POST['height'][$k];
                $data['eur_size'] = $_POST['eur_size'][$k];
                $data['us_size'] = $_POST['us_size'][$k];

                $db->add($data);
            }
                $this->redirect(U('product/user_size_list_1').'&height='.$data['height']);
                exit;
       }

        $this->display();
    }

    public function user_size_edit(){
        $id = $_GET['id'];
        $db = M('user_size_items');
        if(IS_POST){
            $edit_id = $_POST['id'];
            $db->save($_POST);
            $this->redirect('product/user_size_list');
            exit;
        }
        $info  = $db->find($id);
        $this->assign('info',$info);
        $this->display();
    }
    public function user_size_del(){
        $id = $_GET['id'];
        $db = M('user_size_items');
        $db->delete($id);
        $this->redirect(U('product/user_size_list_1').'&height='.$_GET['height']);
    }
    
    public function print_mianliao_list(){
           $mianliao_list =  M('product as p')->join('left join suppliers as s on p.suppliers_id = s.suppliers_id')->where('p.is_sell=1 and p.is_delete=0 and p.suppliers_id!=0 and display=1')->select();
           echo "<table style='text-align:center'><tr><td>商品id</td><td>面料名称</td><td>面料图片</td><td>商品图片</td></tr>";
           foreach($mianliao_list as $k=>$v){
               echo '<tr>';
               echo '<td>'.$v['id'].'</td>';
               echo '<td>'.$v['suppliers_name'].'</td>';
               echo '<td><img src="'.$v['ml_img'].'"></td>';               
               echo '<td><img src="'.$v['goods_img'].'"></td>';
               echo '</tr>';
           }
           echo '</table>';
    }


	function search(){
		$post = $_REQUEST;
		$where = array();
        
        $searchkeyword = trim($post['searchkeyword']);
		if($searchkeyword){
			$searchkeyword = strtolower($searchkeyword);
            $where['keyword'] = array('like','%'.$searchkeyword.'%');
		}
		$this->assign('searchkeyword', $searchkeyword);

	    //用户筛选关键词
		if(isset($post['keyword']) && $post['keyword']){
			if($post['searchtype'] == 0){
				$where['users.email'] = $post['keyword'];
			}else if($post['searchtype'] == 1){
				$where['sid'] = $post['keyword'];
			}
			$this->assign('searchtype', $post['searchtype']);
		    $this->assign('keyword', $post['keyword']);
		}
 
        if(!isset($post['usertype']) || ($post['usertype'] != 2 && $post['usertype'] != 3)){
              $post['usertype'] = 1;
        }

		if($post['usertype'] == 1){
            $where['user_id'] = array('GT',0);
		}else if($post['usertype'] == 3){
			$where['user_id'] = 0;
		}
		$this->assign('usertype', $post['usertype']);
        
        $where['_string'] = '';
        //开始时间
        if( !empty($post['start_time'])){
            $where['_string'] .= ' add_time >= '.strtotime($post['start_time']." 00:00:00");
        }
        $this->assign('start_time', $post['start_time']);

        //开始时间
        if( !empty($post['end_time'])){
            $where['_string'] .= ' and add_time <= '.strtotime($post['end_time']." 23:59:59");
        }
        $this->assign('end_time', $post['end_time']);

        if(empty($where['_string'])) unset($where['_string']);
        //print_r($where);
 
		$search_db = D('search');
		
		$pageRows = 20;
		if(isset($_REQUEST['pageRows']) && intval($_REQUEST['pageRows'])){
			$pageRows = intval($_REQUEST['pageRows']);
		}
		//分页
		$search_db->join('users ON users.id = search.user_id');
		$search_db->order('search.id desc');
		$search_db->where($where);
		$searchList = $search_db->select();
		$count = count($searchList);//总记录数
		import("ORG.Util.Page");// 导入分页类
		$Page = new Page($count, $pageRows);// 实例化分页类 传入总记录数和每页显示的记录数
		$pageShow = $Page->show();// 分页显示输出
		$this->assign('pageShow', $pageShow);

		$search_db->join('users ON users.id = search.user_id');
		$search_db->field('users.email,users.language_id,search.id,search.user_id,search.sid,search.keyword,search.ip,search.add_time,search.result');
		$search_db->order('search.id desc');
		$search_db->where($where);
		$search_db->limit($Page->firstRow.','.$Page->listRows);
		$searchList = $search_db->select();

        //加载IP库
        include(VENDOR_PATH."GeoIp/geoip.inc");
        $gi = geoip_open(VENDOR_PATH."GeoIp/GeoIP.dat",GEOIP_STANDARD);
	    foreach ($searchList as $key => $value) {
	    	// if($value['user_id']>0){
	    	// 	$searchList[$key]['language'] = D('language')->where(array('id'=>$value['language_id']))->getField('name');
	    	// }
	    	$ip = $value['ip'];
	        $geo_code = geoip_country_code_by_addr($gi, $ip);
	        $searchList[$key]['ip_tips'] = $geo_code;
	    }

		$this->assign('searchList', $searchList);
		$this->assign('pageRows', $pageRows);
		$this->display('search');

	} 

    //到货通知邮件
    public function notifyMeEmail($pid){
        
        $notifymeUser = D('notifyme')->field('id,user_id')
           ->where(array('pid'=>$pid,'is_notify'=>0))->select();
        $mailInstance = D(WEB_APP_NAME.'://Email');
        foreach ($notifymeUser as $val) {
        	$user_id = $val['user_id'];
        	$userInfo = UserModel::getUserInfo($user_id);
			$email_template = UserModel::getEmailTemplateInfo('notifymeEmail', $userInfo['language_id']);
			if($email_template){
				$prododuct = ProductModel::get_product_info($pid, $userInfo['language_id']);
                if(!$prododuct) return;
				$title = $email_template['title'];
				$title = str_replace('{$productName}', $prododuct['name'], $title);
				$content = $email_template['content'];
				$content = str_replace('{$productName}', $prododuct['name'], $content);
				$productUrl = 'http://'.$_SERVER['HTTP_HOST'].$prododuct['url'];
				$content = str_replace('{$productUrl}', $productUrl, $content);
				$mailInstance->sendMail($userInfo['email'], $title, $content);
				
				//改成已通知
                D('notifyme')->where(array('id'=>$val['id']))->save(array('is_notify'=>1));
			}
        }     
    }
    //鞋子尺码
    public  function shoes_size_list(){
        $shoes_size_data = D("shoes_size_data");
        //分页
        $count = $shoes_size_data->count();
        import("ORG.Util.Page");
        $Page = new Page($count,20);
        $pageShow = $Page->show();
        $this->assign('pageShow', $pageShow);
        $shoes_size_data->order('cn_size');
        $shoes_size_data->limit($Page->firstRow.','.$Page->listRows);
        // $shoes_size_data->where($where);
        $shoes_size_data_list =$shoes_size_data->select();
        $this->assign('shoes_size_data_list',$shoes_size_data_list);
        $this->display('shoes_size_list');
    }
    public function shoes_size_add(){
        $shoes_size_data = D("shoes_size_data");
        if($_POST['dosubmit']){
            $post['cn_size']=trim($_POST['cn_size']);
            $last_id=$shoes_size_data->add($post);
            if($last_id){
                $this->success('添加成功！', U('product/shoes_size_list'),"add");
            }else{
                $this->error('添加失败！', U('product/shoes_size_add'),"add");
            }

        }else{
            $this->display('shoes_size_add');
        }

    }
    public function shoes_size_edit(){
        $shoes_size_data = D("shoes_size_data");
        $id=intval($_GET['id']);
        $shoes_size=$shoes_size_data->where('id='.$id)->find();
        if($_POST['dosubmit']){
            $post['cn_size']=trim($_POST['cn_size']);
            if($shoes_size_data->where(array('id'=>$id))->save($post)){
                $this->success('修改成功！', U('product/shoes_size_list'),'edit');
            }else{
                $this->error('修改失败！', U('product/shoes_size_edit','id='.$id),'edit');
            }

        }else{
            $this->assign('shoes_size',$shoes_size);
            $this->display('shoes_size_add');
        }
    }
    public function shoes_size_delete(){
        $shoes_size_data = D("shoes_size_data");
        $id=intval($_GET['id']);
        if($shoes_size_data->where(array('id'=>$id))->delete()){
            $this->success('删除成功！', U('product/shoes_size_list'));
        }else{
            $this->error('删除失败！', U('product/shoes_size_list'));
        }
    }
	
	public function product_relation(){
		$productList = array();
		$categorySelectList = CategoryModel::categorySelectList();
		$brandList = CategoryModel::getCategoryListBase(CategoryModel::TYPE_BRAND);
		if(isset($_GET['ids']) && !empty($_GET['ids'])){
			$where['product.id'] = array("in",explode(",",$_GET['ids']));
			$where['product_items.language_id'] = C('language_id');
			$order = 'product.id ASC';
	
			$product_db = D('product');
			$productList = $product_db->field('id,name,img')->join('product_items ON product_items.product_id = product.id')->where($where)->order($order)->select();
		}
		$this->assign('productList', $productList);
		$this->assign('categorySelectList', $categorySelectList);
		$this->assign('brandList', $brandList);
		$this->display();	
	}
	public function plists(){
		
		$post = $_REQUEST;
		
		$language_id = 6;
		$where = array(
				'product.is_delete' => 0,
		);
        
        $is_accessories = false;
		//搜索分类
		if(isset($post['catid']) && $post['catid']){
			$cat_ids = CategoryModel::getCategoryChildIds($post['catid']);
			$where['product.catid'] =  array('in', $cat_ids);
			$catid = $post['catid'];
			$this->assign('catid', $post['catid']);
			if($post['catid'] == 2067){
                $is_accessories = true;
			}else{
				$parentid = D('category')->where(array('id'=>$post['catid']))->getField('parentid');
				if($parentid == 2067) $is_accessories = true;
			}
		}
		
		
		//搜索产品类型
		if(isset($post['modelid']) && $post['modelid']){
			$where['product.model_id'] = $post['modelid'];
			$this->assign('modelid', $post['modelid']);
		}
		//搜索设计师
		if(isset($post['designer_id'])){
			if($post['designer_id'] != -1) $where['product.designer_id'] = $post['designer_id'];
			$this->assign('designer_id', $post['designer_id']);
		}
		//搜索是否预售
		if($post['product_type'] != ''){
			$where['product.product_type'] = $post['product_type'];
			$this->assign('product_type', $post['product_type']);
		}

		//搜索是否上下架
		if($post['display'] != ''){
			$where['product.display'] = $post['display'];
			$this->assign('display', $post['display']);
		}

		//搜索推荐
		if(isset($post['recommendid']) && $post['recommendid']){
			$where['cp.catid'] = $post['recommendid'];
			$this->assign('recommendid', $post['recommendid']);
		}

		//搜索关键词
		if(isset($post['keyword']) && $post['keyword']){
			if($post['searchtype'] == 2)
			{
				$where['product.id'] = $post['keyword'];
            	$catid = D('product')->where(array('id'=>$post['keyword']))->getField('catid');
            	$parentid = D('category')->where(array('id'=>$catid))->getField('parentid');
            	if($catid == 2067 || $parentid ==2067 ){
            		$is_accessories = true;
            	}				
			}elseif($post['searchtype'] == 1)
			{
				$where['product.sn'] = $post['keyword'];
			}elseif($post['searchtype'] == 3)
            {
                $where['product.eng_id'] = $post['keyword'];
            }elseif($post['searchtype']==4){
				$condition['suppliers_name'] = array('like', '%'.$post['keyword'].'%');
				$suppliers_res=D("suppliers")->where($condition)->select();
				if(!empty($suppliers_res)){
					$suppliers_id_arr = array();
					foreach($suppliers_res as $val_suppliers){
						array_push($suppliers_id_arr,$val_suppliers['suppliers_id']);
					}
					$where1['product.suppliers_id'] = array("in",$suppliers_id_arr);
				}
				if(isset($where1)){
					$where2['pri.name'] = array('like', '%'.$post['keyword'].'%');
					$where=array($where1,$where2,'_logic'=>'or');
				}else{
					$where['pri.name'] = array('like', '%'.$post['keyword'].'%');
				}
			}
			$this->assign('keyword', $post['keyword']);
		}
		$this->assign('searchtype', $post['searchtype']);
		if($post['pids']){
			$where['product.id'] = array("in",$post['pids']);
		}
		//搜索是否预售
		if($post['product_type'] != ''){
			$where['product.product_type'] = $post['product_type'];
		}
		
		//order by
		if(isset($_REQUEST['sort_by']) && $_REQUEST['sort_by']){
			$sort_by = $_REQUEST['sort_by'];
		}else{
			$sort_by = 'DESC';
		}
		
		if(isset($_REQUEST['order_by']) && $_REQUEST['order_by']){
			$order_by = $_REQUEST['order_by'];
		}else{
			$order_by = 'id';
		}
		
//		dump($where);exit;
        //到出产品数据
        if( intval($_REQUEST['doexcel']) ==1 ){
            $this->list_doexcel($where, $order_by, $sort_by);exit;
        }

		$product_db = M('product');

		//分页
		if(isset($_SESSION['search']['recommendid'])){
			$product_db->join('category_product as cp on cp.pid=product.id');
		}
		
		
		$pageRows = isset($_SESSION['product_pageRows']) ? $_SESSION['product_pageRows'] : 20;
		if(isset($_REQUEST['pageRows']) && intval($_REQUEST['pageRows'])){
			$pageRows = intval($_REQUEST['pageRows']);
			$_SESSION['product_pageRows'] = $pageRows;
		}
		
		$product_db->where($where);
		$count = $product_db->count();//总记录数
//		echo $product_db->getLastSql();exit;
		import("ORG.Util.Page");// 导入分页类
		$Page = new Page($count, $pageRows);// 实例化分页类 传入总记录数和每页显示的记录数
		$pageShow = $Page->show();// 分页显示输出
		$this->assign('pageShow', $pageShow);
		$nowPage = $Page->getNowPageUrl();//当前页url
		//如果是post过来的则跳转到带参数的url
		if($_POST){
			if($nowPage){
		    	redirect($nowPage);exit;
			}
		}
		//保存当前url
		cookie('product_list_nowPage',$nowPage);			
		//$where['pri.language_id']= $language_id;
		
		//产品列表
//		$product_db->field('product.id');
		$product_db->field('product.eng_id,product.id,product.catid,product.brand_id,product.sn,pri.name,product.sell_price,product.market_price,product.visit,product.stock,product.listorder,product.display,product.custom_price,product.advanced_price,product.is_sell,product.product_type,product.sorts,product.small_img,product.suppliers_id');
		$product_db->join('product_items AS pri ON product.id=pri.product_id and pri.language_id='.$language_id);
		$product_db->order('product.listorder DESC, product.id DESC');
		$product_db->limit($Page->firstRow.','.$Page->listRows);
		$product_db->group('product.id');
		$product_db->where($where);
		$product_db->order( $order_by.' '. $sort_by);
		
		if(isset($_SESSION['search']['recommendid'])){
			$product_db->join('category_product as cp on cp.pid=product.id');
		}
		$productList = $product_db->select();
		//echo M()->getLastSql();


		if($productList){
			$categoryList = CategoryModel::getCategoryListBase();
//			$brandList = CategoryModel::getCategoryListBase(CategoryModel::TYPE_BRAND);
			foreach ($productList as &$product){
				$product['catname'] = '';
//				$product['brand_name'] = '';
				if($product['catid']){
					foreach ($categoryList as $cat){
						if($product['catid'] == $cat['id']){
							$product['catname'] = $cat['name'];
							break;
						}
					}
				}
//				if($product['brand_id']){
//					foreach ($brandList as $brand){
//						if($product['brand_id'] == $brand['id']){
//							$product['brand_name'] = $brand['name'];
//							break;
//						}
//					}
//				}
				if($is_accessories){
					$product['surplus'] = SuppliersModel::inventorySurplus(2,$product['id']);
				}
			}
			unset($product);
		}

//dump($productList);exit;
		$this->assign('productList', $productList);
		//下拉分类
		$catid = isset($catid) ? $catid : 0;
		$select_categorys = CategoryModel::categorySelectList($catid); 
		$this->assign('select_categorys', $select_categorys);
		//属性类型列表
		$modelList = AttributeModel::getModelList(); 
		$this->assign('modelList', $modelList);
		//推荐数组
		$recommendArray = array();
		$recommends = CategoryModel::getCategoryListBase(CategoryModel::TYPE_RECOMMEND);
		foreach ($recommends as $cat){
			$recommendArray[$cat['id']] = $cat['name'];
		}
		$this->assign('recommendArray', $recommendArray);

		//设计师列表
		$designerList = UserModel::getUserDesignerList();
		$this->assign('designerList', $designerList);
        
        $this->assign('is_accessories', $is_accessories);
		$this->assign('search', isset($_SESSION['search']) ? $_SESSION['search'] : null);
		$this->assign('pageRows', $pageRows);
		$this->assign('sort_by', $sort_by);
		$this->assign('order_by', $order_by);
		$this->display('product_list');
	}
	//修改图片排序
	public function updataImgOrder(){
		$img_order_data = $_REQUEST['order_json'];
		$img_order_arr = json_decode($img_order_data,true);
		foreach($img_order_arr as $key=>$v){
			D("product_photo")->where('fid='.$key)->save(array('order' => $v));
		}
		echo "修改完成";
	}
}